#include "Channel.h"
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
#include "Epoll.h"
#include "sockAddrIn.hpp"
#include <thread>
using namespace std;
Channel::Channel(Epoll* ep, int fd) : ep_(ep), fd_(fd) {}
// 这个函数负责分发事件
void Channel::handleEvent() {
    // 对方已关闭，有些系统检测不到
    if (revents_ & EPOLLRDHUP) {
        this->exitCb_();
        return;
    } else if (revents_ & (EPOLLIN | EPOLLPRI)) {
        readCallBack_();
    } else  if (revents_ & EPOLLOUT) {
        writeCallBack_();
    } else {
        errorCb_();
    }
}
void Channel::setReadCb(std::function<void()> fun) {
    readCallBack_ = fun;
}
// void Channel::setOnMsgCb(std::function<void()> fun) {
//     this->readCallBack_ = ;
// }
void Channel::disalbeAll() {
    events_ = 0;
    revents_ = 0;
    ep_->updateChannel(this);
}

void Channel::enableReading() {
    events_ |= EPOLLIN;
    ep_->updateChannel(this);
}

void Channel::disableReading() {
    events_ &= ~EPOLLIN;
    ep_->updateChannel(this);
}

void Channel::enableWriting() {
    events_ |= EPOLLOUT;
    ep_->updateChannel(this);
}
void Channel::disableWriting() {
    events_ &= ~EPOLLOUT;
    ep_->updateChannel(this);
}


void Channel::setET() {
    events_ |= EPOLLET;
    // ep_->updateChannel(this);
}
Channel::~Channel() {}